import { useState, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { ResizableTitle } from './title';
import './index.less';

export default ({ columns = [], ...props }) => {
    const [collapsed, setCollapsed] = useState(true);
    const [tableHeight, setTableHeight] = useState();
    // * 列数据
    const [cols, setCols] = useState(columns);
    const colsArray = cols.map((col, index) => {
        return {
            ...col,
            onHeaderCell: column => ({ width: column.width, onResize: handleResize(index) })
        };
    });

    // 调整列宽
    const handleResize = index => {
        return (_, { size }) => {
            const temp = [...cols];
            temp[index] = { ...temp[index], width: size.width > 60 ? size.width : 60 };
            setCols(temp);
        };
    };
    // 搜索展开收起
    const handleCollapse = (collapsedState) => {
        setCollapsed(collapsedState);
    };

    useEffect(() => {
        listenerResize()
    }, [collapsed])

    const listenerResize = () => {
        const searchHeight = window.document.getElementsByClassName("ant-pro-table-search")[0];
        setTableHeight(props?.scroll?.y - searchHeight.offsetHeight + 80)
    }

    return (
        <ProTable
            components={{ header: { cell: ResizableTitle } }}
            columns={colsArray}
            {...props}
            scroll={{ ...props.scroll, y: tableHeight }}
            search={{
                ...props.search,
                collapsed: collapsed,
                onCollapse: handleCollapse,
            }}
        />
    );
};

